#! /bin/sh
## 服务端自动化编译部署脚本 .Power by terrfly

#引入config
. ./config.sh

##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  环境变量参数设置  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  环境变量参数设置  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  函数定义  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓


##设置setIsInstall
function setIsInstall()
{
	local param=$1
	if [[ "$param" == "--install" ]];then
		isInstall=1
	fi
}


function mvnProject(){

	# 编译项目
	cd $javaProjectResourcePath
	
	#拉取项目
	git pull

	#项目打包
	echo "resources maven package"
	local mvnResult=`mvn package | grep "BUILD"`
	
	##当构建出现异常，直接退出shell
	if [ "$mvnResult" != "[INFO] BUILD SUCCESS" ];then
		echo "[resources] ERROR: mvn pakcage error !  exit 0 !!!!"
		exit 0
	fi
	
	echo "$mvnResult"

	#返回主目录
	cd $currentPath

}

##备份项目并发布
function installProject()
{

	local subAppName=$1
	local subAppRealName="${javaProjectMap[$subAppName]}"

	#进入安装目录
	cd $javaProjectInstallPath/$subAppRealName
	
	echo "" ##换行
    ##备份目录下是否存在当前日期目录（20180712格式），如果不存在则创建目录
	if [ ! -d $javaProjectBackupsPath/$currentDate ]; then 
		  mkdir $javaProjectBackupsPath/$currentDate
	fi
	
	##备份名称 example: i-platform_20180920110101
	local backupFileName=$subAppRealName"_"$currentTime".jar" 
	
	## 压缩并创建到备份目录  -P参数 避免压缩提示 Removing leading `/' from member names
	mv $subAppRealName*.jar $javaProjectBackupsPath/$currentDate/$backupFileName
	echo "[$subAppRealName] backup Success , backupName: $backupFileName"
	
	cp $javaProjectResourcePath/$subAppRealName/target/$subAppRealName*.jar .

	echo "[$subAppRealName] install success."

	#返回主目录
	cd $currentPath

}




##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  函数定义  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

##  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓  1. 检查  ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

##遍历所有参数
for paramItem in $@; do
	setIsInstall $paramItem   ##获取是否安装参数
done

##如第一个参数为null 提示错误信息.
if [ ! -n "$1" ];then
	echo "ERROR: please input appName [${!javaProjectMap[@]}]"
	exit 0
fi

checkJavaProjectName $1 ##调用hasVal,判断项目名是否合法，并返回结果。 1-通过
##当第一个参数不等于all并且不在projects数组中
if [ $? != 1 ];then
	echo "ERROR: appName[$1] is not available!"
	exit 0
fi


##  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑  1. 检查  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑



#构建项目
echo '【1/2】 mvn build ... '
mvnProject



##当isInstall != 1 说明无需安装，直接退出shell.
if [ $isInstall != 1 ];then
	echo '【Done.】'
	exit 0
fi


##停止服务、备份应用、安装应用、重启↓↓↓↓↓↓
echo ""
echo "【2/2】[$substringProjectName] stop/install/restart ..."
if [ "$1" == "all"  ];then	
	./restartJavaServer.sh all stop
	for v in ${!javaProjectMap[@]};do
		installProject "$v"
	done
	./restartJavaServer.sh all start
else
	./restartJavaServer.sh "$1" stop
	installProject "$1"
	./restartJavaServer.sh "$1" start
fi

echo 'Done.'
